import { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { isAuthenticated } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

const WHITE_LIST = ['/login', '/404']

export const authGuard = async (
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext,
) => {
  const userStore = useUserStore()

  // 白名单路由直接通过
  if (WHITE_LIST.includes(to.path)) {
    next()
    return
  }

  // 检查是否已登录
  if (!isAuthenticated()) {
    next(`/login?redirect=${to.path}`)
    return
  }

  // 检查是否已加载用户信息
  if (!userStore.userInfo) {
    try {
      // 获取用户信息
      await userStore.getUserInfo()
      next()
    } catch (error) {
      // 获取用户信息失败，返回登录页
      userStore.logout()
      next(`/login?redirect=${to.path}`)
    }
  } else {
    next()
  }
}
